import { getLayoutProps } from "@/common/layout/getProps";
import { PageContainer } from "@ant-design/pro-layout";
import {
  Button,
  Col,
  Form,
  Input,
  message, Modal,
  Row, Select, Space,
} from "antd";
import Router from "next/router";
import { useRouter } from "next/router";
import { useEffect, useState } from "react";
import styles from "./index.module.scss";
import { useRouter as useNavigationRouter } from "next/navigation";
import { http } from "@/utils/request";


type TableDataType = Record<string, any>;

export const EmployeeVoiceCU = () => {
  const nRouter = useNavigationRouter();
  const router = useRouter();
  const { query } = router;
  const { id, type } = query;
  const [form] = Form.useForm();
  const [editForm] = Form.useForm()
  const [open, setOpen] = useState<boolean>(false);
  const [currentEdit, setCurrentEdit] = useState<Partial<TableDataType>>({});
  const [isReply, setIsReply] = useState(false);

  const isAdd = !id && !type;
  const isEdit = !!id && !type;
  const isDetail = !!id && (type === "detail");

  // const getDetailById = () => {
  //   if (isEdit || isDetail) {
  //     form.setFieldsValue({
  //       suggestionName: "19599595",
  //       issueName: {
  //         label: "企业管理",
  //         value: "10",
  //       },
  //       content: "balabalabala",
  //     });
  //   }
  // }

  useEffect(() => {
    if (isEdit || isDetail) {
      detailSave();
    } else {
      form.setFieldsValue({})
    }
  }, []);

  const handleOk = () => {
    console.log(isReply)
    if(isReply){
      inReply();
    }
    message.success("成功")
    setOpen(false);
  }
  const inReply = async function() {
    const formData = {
      reply: editForm.getFieldValue('reply'),
      opinionId: id
    }
    try {
      const res = await http.post({
        url: "/PmPersonOpinion/add",
        data:formData,
      })
      if(res.code == 200){
        message.success('新增成功')
        Router.push('/employeeVoices')
      }else{
        message.error(res.msg);
      }
    } catch (errorInfo) {
      console.log('Failed:', errorInfo);
    }
  }
  const handleCancel = () => {
    setOpen(false);
  }
  //新增/编辑接口
  const submit = async function(p0: string) {
    const addFormData = {
      suggestionName: form.getFieldValue('suggestionName'),
      issueName: form.getFieldValue('issueName').label,
      content: form.getFieldValue('content'),
      issueCode: form.getFieldValue('issueName').value,
      personId: '1',
      personName: '测试',
      status: p0,
    }
    if(isAdd){
      addSave(addFormData)
    } else if(isEdit){
      addFormData.id = id;

      editSave(addFormData)
    }
  }
  // 新增
  const addSave = async function(formData: object) {
    try {
      const res = await http.post({
        url: "/PmPersonOpinion/add",
        data:formData,
      })
      if(res.code == 200){
        message.success('新增成功')
        Router.push('/employeeVoices')
      }else{
        message.error(res.msg);
      }
    } catch (errorInfo) {
      console.log('Failed:', errorInfo);
    }
  };
  // 详情
  const detailSave = async function() {
    try {
      const res = await http.get({
        url: "/PmPersonOpinion/qryById",
        params:{
          opinionId:id,
        }
      })
      if(res.code == 200){
        form.setFieldsValue({
          suggestionName: res.data.suggestionName,
          issueName: {
            label: res.data.issueName,
            value: res.data.issueCode,
          },
          content: res.data.content,
        });
        console.log(res)
      }else{
        message.error(res.msg);
      }
    } catch (errorInfo) {
      console.log('Failed:', errorInfo);
    }
  };
  // 编辑
  const editSave = async function(formData: object) {
    try {
      const res = await http.put({
        url: "/PmPersonOpinion/update",
        data:formData,
      })
      if(res.code == 200){
        message.success('编辑成功')
        Router.push('/employeeVoices')
      }else{
        message.error(res.msg);
      }
    } catch (errorInfo) {
      console.log('Failed:', errorInfo);
    }
  };

  return (
    <>
      <PageContainer header={{
        title: false
      }}>
        <div className={[styles.formCard, 'mb-[20px]'].join(' ')}>
          <Row>
            <Col span={10}>
              <Form form={form} labelAlign={'left'} labelWrap labelCol={{span: 4}} disabled={isDetail}>
                <Form.Item
                  label={"标题"}
                  name="suggestionName"
                  rules={[{ required: true, message: '请输入标题!' }]}
                >
                  <Input placeholder={"请输入"}></Input>
                </Form.Item>
                <Form.Item
                  label={"问题类型"}
                  name="issueName"
                  rules={[{ required: true, message: '请选择问题类型!' }]}
                >
                  <Select
                    labelInValue
                    options={[
                      { value: '10', label: '企业管理' },
                    ]}
                  ></Select>
                </Form.Item>
                <Form.Item
                  label={"建议内容"}
                  name="content"
                  rules={[{ required: true, message: '请输入建议内容!' }]}
                >
                  <Input.TextArea rows={5} placeholder={"请输入"}></Input.TextArea>
                </Form.Item>
              </Form>
            </Col>
          </Row>

          {
            !isDetail ?
              <Row>
                <Col span={10} className={'text-right'}>
                  <Space>
                    <Button>返回</Button>
                    <Button type={'primary'} onClick={() => submit('0')}>保存</Button>
                    <Button type={'primary'} onClick={() => submit('1')}>提交</Button>
                  </Space>
                </Col>
              </Row>
              :
              <Row>
                <Col span={10} className={'text-right'}>
                  <Space>
                    <Button onClick={() => {
                      router.back();
                    }}>返回</Button>
                    <Button type={'primary'} onClick={() => {
                      setIsReply(true);
                      setCurrentEdit({});
                      setOpen(true);
                    }}>回复</Button>
                    <Button type={'primary'} onClick={() => {
                      setIsReply(false);
                      setCurrentEdit({});
                      setOpen(true);
                    }}>处理</Button>
                  </Space>
                </Col>
              </Row>
          }
        </div>

        <Modal
          open={open}
          title={isReply ? "答复消息" : "问题处理"}
          afterClose={() => editForm.resetFields()}
          onOk={handleOk}
          onCancel={handleCancel}
          okText={'提交'}
          cancelText={'取消'}
          footer={(_, { OkBtn, CancelBtn }) => (
            <>
              <CancelBtn />
              <OkBtn />
            </>
          )}
        >
          <Form form={editForm} initialValues={currentEdit} labelCol={{span: 4}}>
            {
              !isReply ?
                <>
                  <Form.Item
                    label={'处理部门'}
                    name={'field1'}
                  >
                    <Select
                      options={[
                        { value: 'option1', label: 'option1' },
                        { value: 'option2', label: 'option2' },
                        { value: 'option3', label: 'option3' },
                      ]}
                    ></Select>
                  </Form.Item>
                  <Form.Item
                    label={'审批人'}
                    name={'field2'}
                  >
                    <Select
                      options={[
                        { value: 'option1', label: 'option1' },
                        { value: 'option2', label: 'option2' },
                        { value: 'option3', label: 'option3' },
                      ]}
                    ></Select>
                  </Form.Item>
                  <Form.Item
                    label={'转交意见'}
                    name={'field3'}
                  >
                    <Input.TextArea rows={5} placeholder={"请输入"}></Input.TextArea>
                  </Form.Item>
                </>
                :
                <>
                  <Form.Item
                    name={'reply'}
                  >
                    <Input.TextArea rows={5} placeholder={"请输入"}></Input.TextArea>
                  </Form.Item>
                </>
            }
          </Form>
        </Modal>
      </PageContainer>
    </>
  )
}

export const getServerSideProps = getLayoutProps;
export default EmployeeVoiceCU;
